<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>webgl着色器</title>
  <script src="lib/webgl-debug.js"></script>
  <script src="lib/webgl-utils.js"></script>
  <script src="lib/cuon-utils.js"></script>
  <script src="lib/cuon-matrix.js"></script>
</head>

<body onload="main()">
  <canvas id="canvas" width="400" height="490"></canvas>
</body>
<script>
  // 顶点着色器伪代码
  var vShder_source = `
  attribute vec4 position;
  attribute float psize;
void main(){
gl_Position =position; //设置坐标
gl_PointSize =psize; //设置尺寸
}
`
  //片元着色器伪代码
  var fShder_source = `
void main(){
gl_FragColor = vec4(0.5,0.0,0.0,1.0); //设置颜色
}
`
  function main() {
    var canvas = document.getElementById('canvas');
    //  获取上下文对象
    var gl = getWebGLContext(canvas);
    //  初始化着色器
    if (!initShaders(gl, vShder_source, fShder_source)) {
      return;
    }

    var n = initVertexBuffers(gl);
    if (n < 0) {
      console.log("无法获取与顶点相关的数据");
      return;
    }

    // 指定一个覆盖canvas的颜色
    gl.clearColor(0, 0, 0, 1.0);
    // 清除指定的缓冲区
    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.drawArrays(gl.POINTS, 0, n);
  }

  function initVertexBuffers(gl) {

    //顶点坐标和点的尺寸
    var verticesSizes = new Float32Array([
      0.0, 0.5, 10.0,//第一个点
      -0.5, -0.5, 20.0,//第二个点
      0.5, -0.5, 30.0//第三个点

    ])

    // 创建缓冲区
    var vertexSizeBuffer = gl.createBuffer();
    if (!vertexSizeBuffer) {
      console.log("创建缓冲区对象失败");
      return;
    }

    //绑定缓冲区
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexSizeBuffer);
    //项缓冲区写入顶点数据
    gl.bufferData(gl.ARRAY_BUFFER, verticesSizes, gl.STATIC_DRAW);
    // 获取float32Array 中每个元素所占的字节数
    var FSIZE = verticesSizes.BYTES_PER_ELEMENT;

    var position = gl.getAttribLocation(gl.program, "position");
    var psize = gl.getAttribLocation(gl.program, "psize");
    //将缓冲区分配给属性
    //分配到那个属性，几个点，类型，是否归一化，顶点长度，偏移
    gl.vertexAttribPointer(position, 2, gl.FLOAT, false, FSIZE * 3, 0);
    gl.enableVertexAttribArray(position);
    //分配到那个属性，几个点，类型，是否归一化，顶点长度，偏移
    gl.vertexAttribPointer(psize, 1, gl.FLOAT, false, FSIZE * 3, FSIZE * 2);
    gl.enableVertexAttribArray(psize);
    return 3;
  }

</script>

</html>